package com.choudou5.solr.utils;

import com.choudou5.solr.bean.common.SolrQueryParam;
import com.choudou5.solr.util.DateUtil;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;

/**
 * @Name：SqlQueryBuilder 说明
 * @@author choudou5
 * @@date 2018-07-15
 */
public class SolrQueryBuilder extends QueryBuilder {


    /**
     * 构建 查询语句
     * @param req
     * @return
     */
    public static void appendFilterQuery(HttpServletRequest req, SolrQueryParam queryParam) {
        StringBuilder fq = new StringBuilder();
        //构建查询语句
        buildQueryParam(req, fq);
        LogDeBugUtil.debug("查询条件：" + fq.toString());
        queryParam.addFilterQuery(fq.toString());
    }


    public static void appendFilterQuery(SolrQueryParam queryParam, String name, String value) {
        if(StrUtil.isNotBlank(value)){
            String[] arr = StrUtil.split(value, ",");
            StringBuffer sb = new StringBuffer();
            int dex = 0;
            for (String str : arr) {
                if(dex > 0){
                    sb.append(" OR ");
                }
                sb.append(name+":"+str);
                dex++;
            }
            LogDeBugUtil.debug("过滤条件：" + sb.toString());
            queryParam.addFilterQuery(sb.toString());
        }
    }


    //构建查询参数
    private static void buildQueryParam(HttpServletRequest req, StringBuilder where){
        Enumeration<String> paramNames = req.getParameterNames();
        String qType = null;
        String[] array = null;
        int dex = 0;
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String paramVal = req.getParameter(paramName);
            if(StrUtil.isNotBlank(paramVal) && paramName.startsWith(Q_F_PREFIX)){
                //格式：QF__{查询类型}__{字段名}
                //查询类型：EQ=等于， NEQ=不等于，BW=范围，EGT=大于等于，ELT=小于等于
                array = StrUtil.split(paramName, "__");
                if(array.length == 3){
                    paramName = array[2];
                    qType = array[1];
                    //等于
                    switch (qType){
                        case "EQ":
                            where.append((dex > 0 ? " AND " : "") + appendCondition(paramName, ":", paramVal));
                            break;
                        case "NEQ":
                            where.append((dex > 0 ? " AND " : "") + appendCondition(paramName, " !=", paramVal));
                            break;
                        case "LK":
                            where.append((dex > 0 ? " AND " : "") + appendCondition(paramName, " LIKE ",  "%"+paramVal+"%"));
                            break;
                        case "BW":
                            String val = appendCondition(paramName, null, "BW", paramVal);
                            if(val != null) {
                                where.append((dex > 0 ? " AND " : "") + val);
                            }else{
                                dex--;
                            }
                            break;
                        case "EGT":
                            where.append((dex > 0 ? " AND " : "") + appendCondition(paramName, " >= ", paramVal));
                            break;
                        case "ELT":
                            where.append((dex > 0 ? " AND " : "") + appendCondition(paramName, " <= ", paramVal));
                            break;
                    }
                    dex++;
                }
            }
        }
    }

    private static String appendCondition(String paramName, String symbol, String paramVal){
        return appendCondition(paramName, symbol, null, paramVal);
    }

    private static String appendCondition(String paramName, String symbol, String qType, String paramVal){
        if("BW".equals(qType)){
            String[] vals = null;
            if(paramName.contains("Date") || paramName.contains("Time")){
                vals = paramVal.split(" - ");
            }else{
                vals = StrUtil.split(paramVal, ",");
            }
            if(vals.length == 2){
                int state = 0;
                if(StrUtil.isNotBlank(vals[0]))
                    state += 1;
                if(StrUtil.isNotBlank(vals[1]))
                    state += 2;
                if(state==1)
                    return StrUtil.toJavaVariableName(paramName) + "["+ wrapToStr(vals[0]) +" TO NOW]";
                if(state==2)
                    return StrUtil.toJavaVariableName(paramName) + "[* TO " + wrapToStr(vals[1]) +"]";
                if(state==3)
                    return StrUtil.toJavaVariableName(paramName) + "[" + wrapToStr(vals[0]) + " TO " + wrapToStr(vals[1]) +"]";
            }
            return null;
        }
        return paramName + symbol + wrapToStr(paramVal);
    }

    private static String wrapToStr(Object paramVal){
        if(paramVal instanceof String){
            return paramVal.toString();
        }else if(paramVal instanceof Date){
            return DateUtil.toSolrDate((Date) paramVal);
        }else{
            return paramVal==null?null:paramVal.toString();
        }
    }

}
